import fs from "fs";
import path, { resolve } from "path";


// console.log(process.execPath); //返回启动 Node.js 进程的可执行文件的绝对路径名
// console.log(__dirname); //是被执行的js文件的地址
// console.log(process.cwd()); //是当前执行node命令的目录地址
const rootPath = process.cwd();
// 自动处理目录
const checkDirectory = (data: any) => {
  function create(dir: any) {
    var dirname = path.dirname(dir + "/"); // 获取文件的目录
    const isAccess = fs.existsSync(dirname); // 判断是否存在目录

    if (!isAccess) {
      fs.mkdirSync(dirname, { recursive: true }); // 自动创建多层目录  recursive:true 多层
    }
  }
  if (Array.isArray(data)) {
    for (var i = 0; i < data.length; i++) {
      const item = data[i];
      create(item);
    }
  } else if (typeof data == "string") {
    create(data);
  }
};
export const getFile = (url: string) => {
  checkDirectory(url); //检查目录
  try {
    const data = fs.readFileSync(url, "utf8");
    if (data) {
      const jsonData = JSON.parse(data);

      return jsonData;
    }
    return data;
  } catch {
    return;
  }
};
type Flag = "w" | "a" | "ax" | "wx";
// flag w覆盖 a 追加  wx 覆盖，无文件抛错  ax 追加，无文件抛错
export const addFile = (url: string, data: any, flag: Flag = "w") => {
  checkDirectory(url); //检查目录
  const isA = flag == "a" ? "\r\n" : "";
  fs.writeFile(url, JSON.stringify(data) + isA, { flag }, (err) => {
    if (!err) {
    }
  });
};

export const getFileLength = (url: string, length = 50) => {
  checkDirectory(url); //检查目录
  try {
    const data = fs.readFileSync(url, "utf8");

    if (data) {
      const rarr: any = [];
      const arr: any = data.split("\r\n");
      length = length * -1;
      const newArr = arr.slice(length);
      newArr.forEach((v: any) => {
        if (v) {
          const obj = JSON.parse(v);
          rarr.push(obj);
        }
      });
      return rarr;
    }
    return [];
  } catch {
    return [];
  }
};

const getName = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const time =
    new Date().getTime().toString() + Math.floor(Math.random() * 10000);

  const name = `${year}${month}${day}`;
  const url = `/image/${year}/${month}/${time}.jpg`;
  return url;
};
export const uploadImage = (data: any) => {
  return new Promise((resolve, reject) => {
    let url = getName();

    const newurl = `${rootPath}${url}`;
    const buffer = Buffer.from(data);
    checkDirectory(newurl); //检查目录

    const datas = fs.writeFile(newurl, buffer, (err) => {
      if (err) {
        reject();
        return;
      }
      resolve(url);
    });
  });
};
